package com.tsfyun.scm.declarechannel.util;


import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.tsfyun.scm.declarechannel.config.DeclareConfig;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
public class GrabSinglewindow {

    public static void obtainCookie(Integer size) {
        WebDriver driver = null;
        try{
            log.info(String.format("开始尝试第【%s】次",size.toString()));
            System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
            driver = new ChromeDriver();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.navigate().to("http://app.singlewindow.cn/cas/login?_local_card_flag=1&service=http%3A%2F%2Fapp.singlewindow.cn%2Fcas%2Fjump.jsp%3FtoUrl%3DaHR0cDovL2FwcC5zaW5nbGV3aW5kb3cuY24vY2FzL29hdXRoMi4wL2F1dGhvcml6ZT9jbGllbnRfaWQ9c3owMDAwMDAwMFZlNFM5SjAxNCZyZXNwb25zZV90eXBlPWNvZGUmcmVkaXJlY3RfdXJpPWh0dHAlM0ElMkYlMkZzei5zaW5nbGV3aW5kb3cuY24lMkZkeWNrJTJGT0F1dGhMb2dpbkNvbnRyb2xsZXI%3D&configInfoB64=JmNvbG9yQTE9ZDFlNGZiJmNvbG9yQTI9NjYsIDEyNCwgMTkzLCAwLjg%3D&_local_login_flag=1&logoutFlag=1&localServerUrl=http%3A%2F%2Fsz.singlewindow.cn%2Fdyck&localDeliverParaUrl=%2Fdeliver_para.jsp");
            WebElement passwordElement = driver.findElement(By.id("password"));
            passwordElement.sendKeys("88888888");
            WebElement loginbutton = driver.findElement(By.id("loginbutton"));
            Thread.sleep(5000);
            driver.navigate().to("http://sz.singlewindow.cn/dyck/swProxy/deskserver/sw/deskIndex?menu_id=dec001");
            Thread.sleep(2000);
            Set<Cookie> cookies = driver.manage().getCookies();
            List<String> cookieList = new ArrayList<String>();
            cookies.stream().forEach(cookie -> {
                cookieList.add(String.format("%s=%s",cookie.getName(),cookie.getValue()));
            });
            String cookieStr = String.join("; ",cookieList);
            log.info(String.format("成功获取到COOKIE【%s】",cookieStr));

        }catch (Exception e){
            log.info("自动登录失败：",e);
            if(size<3){//尝试
                GrabSinglewindow.obtainCookie(size+1);
            }
        }finally {
            if(Objects.nonNull(driver)){
                driver.quit();
            }
        }
    }

    private static final String COOKIE = "loginSignal=0; JSESSIONID=C4B49C0381A010FF8F37E3372037D4F5; !Proxy!route1plat=0b7d44f74a7c76aa5ed00f65af4cb367; !Proxy!JSESSIONID=e370f428-ab59-4336-8371-c1aa7c632221";
    public static void startRefreshHsCode(String hsCode){
        log.info("海关编码：{}",hsCode);
        String response = HttpRequest.get("http://sz.singlewindow.cn/dyck/swProxy/decserver/sw/dec/common/getGoodsElem?keyValue="+hsCode+"&_="+new Date().getTime()).addHeaders(new HashMap<String, String>(){{
            put("Cookie",COOKIE);
            put("Host","sz.singlewindow.cn");
            put("Origin","http://sz.singlewindow.cn");
            put("Referer","http://sz.singlewindow.cn/dyck/swProxy/decserver/sw/dec/cusCiqZhImport?cusIEFlag=I&dclTrnRelFlag=0&ngBasePath=http%3A%2F%2Fsz.singlewindow.cn%3A80%2Fdyck%2FswProxy%2Fdecserver%2F");
            put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");
        }}).execute().body();
        System.out.println(response);
    }

    public static void getEnterInfo(){
        //0：海关代码 1：组织机构代码 3：企业名称 4：检验检疫编码
        Map<String,String> params = new HashMap<>();
        params.put("enterCode","3702960FCP");
        params.put("queryFlag","0");
                                          //http://sz.singlewindow.cn/dyck/swProxy/decserver/sw/dec/merge/getEnterInfo
        String response = HttpRequest.post("http://sz.singlewindow.cn/dyck/swProxy/decserver/sw/dec/merge/getEnterInfo").addHeaders(new HashMap<String, String>(){{
            put("Cookie",COOKIE);
            put("Host","sz.singlewindow.cn");
            put("Origin","http://sz.singlewindow.cn");
            put("Referer","http://sz.singlewindow.cn/dyck/swProxy/decserver/sw/dec/cusCiqZhImport?cusIEFlag=I&dclTrnRelFlag=0&ngBasePath=http%3A%2F%2Fsz.singlewindow.cn%3A80%2Fdyck%2FswProxy%2Fdecserver%2F");
            put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");
            put("Content-Type","application/json");
        }}).body(JSON.toJSONString(params)).execute().body();
        System.out.println(response);
    }

    public static void downCustoms(String cusCiqNo){
        HttpRequest httpRequest = HttpRequest.get(String.format("http://sz.singlewindow.cn/dyck/swProxy/decserver/entries/ftl/1/0/0/%s.pdf",cusCiqNo)).addHeaders(new HashMap<String, String>(){{
            put("Cookie",COOKIE);
            put("Host","sz.singlewindow.cn");
            put("Origin","http://sz.singlewindow.cn");
            put("Referer","http://sz.singlewindow.cn/dyck/swProxy/decserver/sw/dec/cusCiqZhImport?cusIEFlag=I&dclTrnRelFlag=0&ngBasePath=http%3A%2F%2Fsz.singlewindow.cn%3A80%2Fdyck%2FswProxy%2Fdecserver%2F");
            put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");
        }});
        httpRequest.setConnectionTimeout(10000).setReadTimeout(12000);
        byte[] bytes =  httpRequest.execute().bodyBytes();
        FileUtil.writeBytes(bytes, DeclareConfig.DECCUS_PATH+"pdf/"+cusCiqNo+".pdf");
    }
}
